#define GLOBAL_CPP
#include "global.h"

#include <QSettings>
#include <QDateTime>
#include <QtNetwork/qnetworkinterface.h>

static const uint magic1 = 0x4A8F9C6E;
static const uint magic2 = 0x0058CF79;

ulong generateUserId()
{
    QList<QNetworkInterface> netlist = QNetworkInterface::allInterfaces();
    QByteArray mac(DEFAULT_MAC);
    quint64 id = mac.toULongLong(0, 16);
    foreach (QNetworkInterface net, netlist) {
        mac = net.hardwareAddress().remove(':').toLatin1();
        id += mac.toULongLong(0, 16);
    }
    id = (id^magic1) + magic2;

    return id;
}

int analyzeFilmSerial(quint64 serial)
{
    QSettings settings;
    long count = 0;
    ulong uid = settings.value(USER_ID).toInt();
    qint32 prevSecs = settings.value(LAST_MODIFIED).toInt();
    quint32 temp2 = uid*magic1+magic2;
    qint32 curSecs = (serial>>32)^temp2;
    if (prevSecs < curSecs) {
        qint32 temp1 = serial^temp2;
        temp1 -= qint32(magic2);
        if ((temp1%17) == 0) {
            count = temp1/17;
            settings.setValue(LAST_MODIFIED, curSecs);
        }
    }
    return count;
}

quint64 getFilmCount()
{
    QSettings settings;
    quint64 num = settings.value(FILM_AVAIL, 0).toULongLong();
    quint64 temp1 = (num>>16)^magic1;
    if (((temp1*magic2)&0xFFFF) == (num&0xFFFF)) {
        if ((temp1-magic2)%17 == 0)
            return (temp1-magic2)/17;
        else return 0;
    }
    else return 0;
}

void setFilmCount(int count)
{
    QSettings settings;

    quint64 temp1 = count*17+magic2;
    quint64 encrypted = ((temp1^magic1)<<16) + ((temp1*magic2)&0xFFFF);
    settings.setValue(FILM_AVAIL, encrypted);
}

QSizeF getPaperSize(PaperSize size)
{
    switch (size) {
    case PS_A4:
        return QSizeF(210, 297);
    case PS_A3:
        return QSizeF(297, 420);
    case PS_A5:
        return QSizeF(148, 210);
    case PS_B4:
        return QSizeF(250, 353);
    case PS_B5:
        return QSizeF(176, 250);
    case PS_Legal:
        return QSizeF(215.9, 355.6);
    case PS_Letter:
        return QSizeF(215.9, 279.4);
    default:
        return QSizeF();
    }
}
